package com.tianxin.workbao.workBao.Activity;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.adapter.SelectCoalAdapter;
import com.tianxin.workbao.workBao.bean.Coal;
import com.tianxin.workbao.workBao.bean.Contract;
import com.tianxin.workbao.workBao.bean.CtCoaltype;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.CoalProvide;
import com.tianxin.workbao.workBao.dataProvide.ContractCoalProvide;
import com.tianxin.workbao.workBao.holder.SelectCoalHolder;
import com.tianxin.workbao.workBao.listener.MyPopupWindowListener;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.ToastUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by hacker on 2017/7/26.
 */

public class AddContractCoalActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener, MyPopupWindowListener {

    private FloatingActionButton saveFab;
    private EditText priceET;
    private EditText weightET;
    private EditText moneyET;
    private TextView coalTV;
    private TextView supplyTv;
    private TextView customerTv;
    private TextView contractTypeTv;
    private final int POPUP_TYPE_COAL = 0;
    private Contract mContract;
    private CtCoaltype mCtCoaltype;
    private PopupWindow popupWindow;
    private List<Coal> mCoalList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_contract_coal_option);
        super.initStatusBar(true);

        initData();
        initView();
        initEvent();
        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("增加合同煤种");
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        saveFab = (FloatingActionButton) findViewById(R.id.save_fab);
        priceET = (EditText) findViewById(R.id.price);
        weightET = (EditText) findViewById(R.id.weight);
        moneyET = (EditText) findViewById(R.id.money);
        coalTV = (TextView) findViewById(R.id.coal_name);
        supplyTv = (TextView) findViewById(R.id.supply_company);
        customerTv = (TextView) findViewById(R.id.customer_company);
        contractTypeTv = (TextView) findViewById(R.id.contract_type);
    }

    @Override
    public void initData() {
        mCtCoaltype = new CtCoaltype();
        Bundle bundle = getIntent().getExtras();
        mContract = (Contract) bundle.getSerializable("contract");
        mCtCoaltype.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        mCtCoaltype.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "0"));
        mCtCoaltype.setStatus(1);
        mCtCoaltype.setIsis(1);
        mCtCoaltype.setContractid((int) mContract.getId());
        mCtCoaltype.setContractnum(mContract.getCtnum());
        mCtCoaltype.setCttype(mContract.getCttype());
    }


    @Override
    public void initEvent() {
        //navigationIcon event
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddContractCoalActivity.this.finish();
            }
        });
        saveFab.setOnClickListener(this);
        coalTV.setOnClickListener(this);

    }

    @Override
    public void bindView() {
        if (mContract.getCttype() == Contract.CONTRACT_CPTYPE_IN) {
            contractTypeTv.setText(" 采购合同");
            supplyTv.setText(supplyTv.getText().toString() + " " + mContract.getSalername());
            customerTv.setText(customerTv.getText().toString() + " " + mContract.getBuyername());
        } else {
            contractTypeTv.setText(" 销售合同");
            supplyTv.setText(supplyTv.getText().toString() + " " + mContract.getBuyername());
            customerTv.setText(customerTv.getText().toString() + " " + mContract.getSalername());
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.save_fab:
                addCoal();
                break;
            case R.id.coal_name:
                getCoalList();
                break;

        }
    }

    /**
     * add Coal Price
     */
    private void addCoal() {
        if (mCtCoaltype.getCoaltypeid() == null ||
                mCtCoaltype.getCoaltypename() == null) {
            showMessage("请选择煤种");
            mCtCoaltype.setCoaltypename(null);
            mCtCoaltype.setCoaltypeid(null);
            coalTV.setText("点击选择煤种");
        }
        float contractunitprice = Float.valueOf(0);
        try {
            contractunitprice = Float.valueOf(priceET.getText().toString());
        } catch (Exception e) {
            showMessage("请正确输入合同价格");
            priceET.setText("");
            priceET.setFocusable(true);
            return;
        }
        if (contractunitprice > 0) {
            mCtCoaltype.setContractunitprice(contractunitprice);
        } else {
            showMessage("请正确输入合同价格");
            priceET.setText("");
            priceET.setFocusable(true);
            return;
        }
        float weight = Float.valueOf(0);
        try {
            weight = Float.valueOf(weightET.getText().toString());
        } catch (Exception e) {
            showMessage("签订吨数输入不正确！");
            weightET.setText("");
            weightET.setFocusable(true);
            return;
        }
        if (weight > 0) {
            mCtCoaltype.setSignweight(weight);
        } else {
            showMessage("签订吨数输入不正确！");
            weightET.setText("");
            weightET.setFocusable(true);
            return;
        }
        float money = Float.valueOf(0);
        try {
            money = Float.valueOf(moneyET.getText().toString());
        } catch (Exception e) {
            showMessage("签订金额输入不正确！");
            moneyET.setText("");
            moneyET.setFocusable(true);
            return;
        }
        if (money > 0) {
            mCtCoaltype.setSignamount(money);
        } else {
            showMessage("签订金额输入不正确！");
            moneyET.setText("");
            moneyET.setFocusable(true);
            return;
        }
        mCtCoaltype.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        mCtCoaltype.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "0"));
        mCtCoaltype.setAddtime(new Date());

        getContractCoalProvide().save(mCtCoaltype);
    }


    @Override
    public void showMessage(String msg) {
        if (msg == "ok") {
            this.finish();
        } else if (msg.contains("failure")) {
            ToastUtils.showLong("添加煤种失败！\n " +
                    msg.substring(msg.indexOf("failure") + 1, msg.length()));
        } else {
            ToastUtils.showShort(msg);
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 1200);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof List) {
            if (((List) result).size() > 0) {
                if (((List) result).get(0) instanceof Coal) {
                    mCoalList = (List<Coal>) result;
                    if (mCoalList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_COAL);
                    } else {
                        showMessage("没有煤种，请到基础数据里查看");
                    }
                }
            }
        } else {
            showMessage("response other information");
        }
    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    private void getCoalList() {
        getCoalProvide().getAllCoals();
    }

    public ContractCoalProvide getContractCoalProvide() {
        return new ContractCoalProvide(this, this);
    }

    public CoalProvide getCoalProvide() {
        return new CoalProvide(this, this);
    }

    @Override
    public void OnMyClick(Integer selectType, Integer id, String information) {
        switch (selectType) {
            case Constant.SELECT_TYPE_COAL:
                dismissPoPup();
                mCtCoaltype.setCoaltypeid(id);
                mCtCoaltype.setCoaltypename(information);
                coalTV.setText(information);
                break;
        }
    }

    private void dismissPoPup() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    private void showSelectPopup(int type) {
        popupWindow = new PopupWindow();
        switch (type) {
            case POPUP_TYPE_COAL:
                SelectCoalAdapter selectCoalAdapter = new SelectCoalAdapter(mCoalList, this, this);
                SelectCoalHolder selectCoalHolder = new SelectCoalHolder(this, this, selectCoalAdapter);
                popupWindow.setContentView(selectCoalHolder.getContentView());
                popupWindow.setHeight(340);
                break;
        }
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.write)));
        popupWindow.setAnimationStyle(R.style.my_popup_animation_style);
        popupWindow.showAtLocation(mToolbar, Gravity.TOP, 0, 0);
    }
}
